package com.r2coding.domain.strategy.service.rule.impl.center;

import com.r2coding.domain.strategy.model.entity.RuleActionEntity;
import com.r2coding.domain.strategy.model.entity.RuleMatterEntity;
import com.r2coding.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.r2coding.domain.strategy.repository.IStrategyRepository;
import com.r2coding.domain.strategy.service.annotation.LogicStrategy;
import com.r2coding.domain.strategy.service.rule.IRuleLogicFilter;
import com.r2coding.domain.strategy.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author caolx
 * @description 奖品解锁条件 规则校验
 * @date 2025/8/4 10:31
 */
@Slf4j
@Service
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_LOCK)
public class RuleLockLogicFilter implements IRuleLogicFilter<RuleActionEntity.RaffleCenterEntity> {

    @Resource
    private IStrategyRepository strategyRepository;

    // 用户抽奖次数，后续完成这部分流程的开发，从数据库/Redis中读取
    private Long userRaffleCount = 0L;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleCenterEntity> filter(RuleMatterEntity ruleMatterEntity) {
        String userId = ruleMatterEntity.getUserId();
        Long strategyId = ruleMatterEntity.getStrategyId();
        String ruleModel = ruleMatterEntity.getRuleModel();

        log.info("规则过滤-次数锁 userId: {}, strategyId: {}, ruleModel: {}", userId, strategyId, ruleModel);

        // 查询规则值配置：当前奖品ID，抽奖中规则对应的校验值。如：1、2、6
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleMatterEntity.getAwardId(), ruleModel);
        long raffleCount = Long.parseLong(ruleValue);

        // 用户抽奖次数大于规则限定值，规则放行
        if (userRaffleCount >= raffleCount) {
            return RuleActionEntity.<RuleActionEntity.RaffleCenterEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }

        // 用户抽奖次数小于规则限定值，规则拦截
        return RuleActionEntity.<RuleActionEntity.RaffleCenterEntity>builder()
                .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                .build();

    }
}
